package com.course.android.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.baselib.android.event.EventManager;
import com.baselib.android.utils.ToastTool;
import com.course.android.R;
import com.course.android.service.DownLoadService;
import com.course.android.ui.view.NumberProgressBar;
import com.course.config.UrlConfig;
import com.course.controller.permission.PermissionController;
import com.course.controller.permission.PermissionReqCode;
import com.course.event.EventBusKey;
import com.course.event.EventVo;
import com.course.model.resp.Version;
import org.apache.commons.lang.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class VersionActivity extends Activity {

    NumberProgressBar npb;
    Version m;
    TextView tv_title, tv_update_info;
    View ll_close, btn_ok;
    private static final int Install_Apk_Req_Code = 10086;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_version);
        tv_title = findViewById(R.id.tv_title);
        btn_ok = findViewById(R.id.btn_ok);
        ll_close = findViewById(R.id.ll_close);
        tv_update_info = findViewById(R.id.tv_update_info);
        npb = findViewById(R.id.npb);

        m = (Version) getIntent().getSerializableExtra("m");
        tv_title.setText("是否要升级到最新版本？");

        tv_update_info.setText("修复已知问题");
        ll_close.setVisibility(View.VISIBLE);

        EventManager.getInstance().register(this);
        //npb.setMax(100);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog permissionDialog = PermissionController.getPersissionDialog(VersionActivity.this,
                        PermissionReqCode.REQ_SELECT_ALBUM);
                if (permissionDialog == null) {
                    btn_ok.setVisibility(View.GONE);
                    npb.setVisibility(View.VISIBLE);
                    if (PermissionController.
                            requestPermissions(VersionActivity.this,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100)) {
                        ToastTool.show(VersionActivity.this,"12354");
                        Intent versionIntent = new Intent(VersionActivity.this, DownLoadService.class);
                        versionIntent.putExtra("url", UrlConfig.getImageUrl(m.getUrl()));
                        ToastTool.show(VersionActivity.this,UrlConfig.getImageUrl(m.getUrl()));
                        startService(versionIntent);

                    }
                    return;
                }else {
                    ToastTool.show(VersionActivity.this,"AAA");
                }
                permissionDialog.show();
            }
        });
        findViewById(R.id.ll_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;//不执行父类点击事件
        }
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }

    @Override
    protected void onDestroy() {
//        unregisterReceiver(reiever);
        EventManager.getInstance().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(EventVo event) {
        if (event == null || StringUtils.isBlank(event.getName())) {
            return;
        }

        if (StringUtils.equals(event.getName(), EventBusKey.APK_DOWNLOAD_OK)) {
            ToastTool.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_LONG).show();
            npb.setProgress(100);
        }
        if (StringUtils.equals(event.getName(), EventBusKey.APK_DOWNLOAD_FAIL)) {
            ToastTool.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_LONG).show();
            npb.refreshDrawableState();
            npb.setProgress(0);
            finish();
        }
        if (StringUtils.equals(event.getName(), EventBusKey.APK_DOWNLOAD_RATE)) {
            int pro = (int) event.getValueByKey(EventBusKey.APK_DOWNLOAD_RATE_VAL);
            npb.setProgress(pro);
        }
        if (StringUtils.equals(event.getName(), EventBusKey.APK_DOWNLOAD_INSTALL)) {
            String path = event.getValueByKey(EventBusKey.APK_DOWNLOAD_INSTALL_KEY).toString();
            m.setLocalPah(path);
            if (PermissionController.canRequestPackageInstalls(this)) {
                ToastTool.show(VersionActivity.this,path);
                PermissionController.installApk(this, m.getLocalPath());
                return;
            }

            try {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, Install_Apk_Req_Code);
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            //再次执行安装流程，包含权限判等
            PermissionController.installApk(this, m.getLocalPath());
        }
    }


}
